package name.marz.to.go.ahg.mhbk.executer;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import name.marz.to.go.ahg.common.util.HttpUtil;
import name.marz.to.go.ahg.core.AutoGetterHttpClient;
import name.marz.to.go.ahg.core.Parameters;
import name.marz.to.go.ahg.core.checker.DocumentChecker;
import name.marz.to.go.ahg.core.exception.InvalidDocumentException;
import name.marz.to.go.ahg.core.executer.AbstractPostExecuter;
import name.marz.to.go.ahg.core.responsehandler.DocumentResponseHandler;

import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

public class MHBKUserNumberExecuter extends AbstractPostExecuter<Document> {
//	private static final Logger log = Logger.getLogger(MHBKUserNumberExecuter.class.getName());
	private final ResponseHandler<Document> handler;
	private final DocumentChecker checker = new MHBKUserNumberChecker();
	private final Document doc;
	private final String userNum;

	{
		super.setPageName("お客様番号入力");
	}
	
	public MHBKUserNumberExecuter(URI uri,AutoGetterHttpClient client, Document doc, String userNum) {
		super(uri, client);
		this.handler = new DocumentResponseHandler(client.getDefaultCharset());
		this.doc = doc;
		this.userNum = userNum;
	}
	
	@Deprecated
	public MHBKUserNumberExecuter(AutoGetterHttpClient client, Document doc, String userNum) {
		super((URI)null, client);
		// ログアウト用URLの取得1
		final String FORM_ID="LOGBNK_00000B";
		Elements es = doc.getElementsByTag("form").select("[name="+FORM_ID+"]");
		if ( es.isEmpty() )  throw new InvalidDocumentException("FORM "+FORM_ID+"が見つかりません",doc);
		super.uri = HttpUtil.createURISafety(es.first().attr("action"));
		this.doc = doc;
		this.handler = new DocumentResponseHandler(client.getDefaultCharset());
		this.userNum = userNum;
	}
	
	@Override
	protected List<NameValuePair> getRequestParameters() {
		Parameters p = HttpUtil.getParametersFromInputTags(doc);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("txbCustNo", userNum));
		params.add(p.getNameValuePair("pm_fp"));
		params.add(p.getNameValuePair("_FRAMEID"));
		params.add(p.getNameValuePair("_TARGETID"));
		params.add(p.getNameValuePair("_LUID"));
		params.add(p.getNameValuePair("_TOKEN"));
		params.add(p.getNameValuePair("_FORMID"));
		params.add(p.getNameValuePair("_SUBINDEX"));
		params.add(p.getNameValuePair("POSTKEY"));
	   return params;
	}

	@Override
	protected DocumentChecker getChecker() {
		return checker;
	}
	
	public String getHost() {
		return uri.getHost();
	}

	@Override
	protected ResponseHandler<Document> getResponseHandler() {
		return handler;
	}
}